﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace Pibby.Core.Feeds
{
	public class FeedFactory
	{
		public Feed CreateFeed(string feedContent)
		{
			try
			{
				var feed = this.CreateFeed(feedContent, FeedType.RSS);

				return feed;
			}
			catch (FeedReadException)
			{
				var feed = this.CreateFeed(feedContent, FeedType.Atom);

				return feed;
			}
		}

		public Feed CreateFeed(string feedContent, FeedType attemptFeed)
		{
			using (var reader = new StringReader(feedContent))
			{
				switch (attemptFeed)
				{
					case FeedType.RSS:

						return ParseRss(reader);

					case FeedType.Atom:

						return ParseAtom(reader);

					default:
						throw new NotSupportedException(string.Format("{0} is not supported", attemptFeed.ToString()));
				}
			}
		}

		private Feed ParseRss(TextReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");

			var settings = new XmlReaderSettings();
			settings.IgnoreComments = true;
			settings.IgnoreProcessingInstructions = true;
			settings.IgnoreWhitespace = true;
			settings.DtdProcessing = DtdProcessing.Ignore;

			using (var xmlReader = XmlTextReader.Create(reader, settings))
			{
				var feedReader = new RssFeedReader();

				return feedReader.Read(xmlReader);
			}
		}

		private Feed ParseAtom(TextReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");

			var settings = new XmlReaderSettings();
			settings.IgnoreComments = true;
			settings.IgnoreProcessingInstructions = true;
			settings.IgnoreWhitespace = true;
			settings.DtdProcessing = DtdProcessing.Ignore;

			using (var xmlReader = XmlTextReader.Create(reader, settings))
			{
				var feedReader = new AtomFeedReader();

				return feedReader.Read(xmlReader);
			}
		}
	}
}
